<?php
/**
 * 购买管理
 */
defined('BASEPATH') OR exit("No direct script access allowed");

class Banding extends CI_Controller{

	//构造初始化函数
	public function __construct(){
		parent::__construct();

		//加载数据库
		$this->load->database();

		// //加载admin模型
		$this->load->model('admin/Doctor_model','doctor');
		$this->load->model('admin/DoctorJ_model','doctorj');

		//加载表单验证规则
		$this->load->library('form_validation');
		date_default_timezone_set("PRC");
	}

	/*
	 * 检查登陆状态
	 */
	public function index()
	{
		if (!$this->session->userdata('upId')){
			echo "<script>alert('你进行了违规操作');location.href ='http://www.yishengqiao.com/1/index.php/doctor/Login';</script>";
		}

		$CODE=$this->input->get('code',TRUE);
		$STATE=$this->input->get('state',TRUE);

		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8ae5b39b702fd858&secret=2d5a5170b3340d10550642f35b74d4b8&code=$CODE&grant_type=authorization_code";
		$contents = file_get_contents($url);
		//如果出现中文乱码使用下面代码
		//$getcontent = iconv("gb2312", "utf-8",$contents);
		// echo $contents; 
		$data=(Array)json_decode($contents);

		//查到openid后，将openid和对应的id更新上去
		//开始更新doctor表，id是upId
		//根据用户名和密码去查找它的doctorID
		//
		//echo $data['unionid'];

		//根据unionID去查找doctorJ表中是否有记录
		$weichat=$this->doctorj->getOneByOpenid($data['unionid']); 
		
		if(!isset($weichat)){
			echo "<script>alert('请先使用该微信登录APP');location.href ='http://www.yishengqiao.com/1/index.php/doctor/Login';</script>";
			exit();
		};

		if(empty($weichat)){
			echo "<script>alert('请先使用该微信登录APP');location.href ='http://www.yishengqiao.com/1/index.php/doctor/Login';</script>";
			exit();
		}


		if ($this->doctor->cheWeichat($data['unionid'])){
			echo "<script>alert('你的微信号已经被绑定过了，不能重复绑定');location.href ='http://www.yishengqiao.com/1/index.php/doctor/Login';</script>";
			exit();
		}

		$updata['weichat']=$data["unionid"];
		$updata['doctorid']=$weichat['id'];
		$w=$this->session->userdata('upId');

		if($this->doctor->updateOne($w,$updata)){
			$this->session->set_userdata('doctorId',$weichat['id']);
			echo "<script>alert('绑定成功');location.href ='http://www.yishengqiao.com/1/index.php/doctor/Patient/index';</script>";
		}
		
	}


}
